from django import forms
from web import models
from django.core.exceptions import ValidationError


class ProjectModelForm(forms.ModelForm):
    # desc = forms.CharField(label='描述',widget=forms.Textarea())
    class Meta:
        model = models.Project
        fields = ['name', 'color', 'desc']
        # 添加小插件
        widgets = {
            'desc': forms.Textarea,
            'color': forms.RadioSelect
        }

    def __init__(self, request, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.request = request
        for name, field in self.fields.items():
            if name in ['color']:
                continue
            field.widget.attrs['class'] = 'form-control'
            field.widget.attrs['placeholder'] = '请输入{}'.format(field.label)

    def clean_name(self):
        """项目进行校验"""
        name = self.cleaned_data['name']
        # 当前用户是否已经创建过此项目
        exists = models.Project.objects.filter(name=name, creator=self.request.tracer.user).exists()
        if exists:
            raise ValidationError('项目名称已存在')
        # 当前用户是否还有额度创建
        # 最多创建N个项目
        # self.request.tracer.price_policy.project_num

        # 已经创建多少个项目
        count = models.Project.objects.filter(creator=self.request.tracer.user).count()
        if count >= self.request.tracer.price_policy.project_num:
            raise ValidationError('您的额度已用完，请开通vip')
        return name
